package JUC.printWhen5;


import myMapReduce.C;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @className: CyclicBarrier
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/4 21:14
 */
public class CyclicBarrierList {
    private List<Integer> list = new ArrayList<>();
    public void add(Integer i){
        list.add(i);
    }
    public int size(){
        return list.size();
    }
    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(2);
        CyclicBarrier cb2 = new CyclicBarrier(2);
        CyclicBarrierList list = new CyclicBarrierList();
        Runnable r1 = () ->{
//            while(true){
                for(int i = 0 ; i < 10 ; i++){
                    list.add(i);
                    System.out.println("add " + i);
                    if(list.size() == 4){
                        try {
                            cb.await();
                            cb.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
//            }
        };

        Runnable r2 = () ->{
//            while(true){
                try {
                    cb.await();
                    System.out.println("list size is " + list.size());
                    cb.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
//            }
        };

        ThreadPoolExecutor pool = new ThreadPoolExecutor(2 , 2 ,
                1000 , TimeUnit.SECONDS , new ArrayBlockingQueue<>(100));
        pool.execute(r1);
        pool.execute(r2);
        pool.shutdown();
    }
}
